package com.varton;

import com.varton.annotation.Autowired;
import com.varton.annotation.Controller;
import com.varton.annotation.Service;
import com.varton.test.UserController;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.*;

public class DispatchSevlet extends HttpServlet {
    private Properties resource = new Properties();
    private Map<String,Object> beansMap = new HashMap<String,Object>();
    private List<String> classNames = new ArrayList<String>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }

    @Override
    public void init(ServletConfig config) throws ServletException {

        //定位资源
        doResource(config.getInitParameter("contextConfigLocation"));
        //扫描-加载资源
        doLoadResource(resource.getProperty("scanner.path"));
        //注册
        doRegister();
        //注入
        doDepandent();

        UserController userController = (UserController) beansMap.get("userController");
        userController.getUser();
    }

    private void doResource(String configLocation) {
        InputStream is = this.getClass().getClassLoader().getResourceAsStream(configLocation.replace("classpath:",""));
        try {
            resource.load(is);
        } catch (IOException e) {
            e.printStackTrace();
            if (is != null){
                try {
                    is.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    private void doLoadResource(String packageName) {
        try {
            URL url = this.getClass().getClassLoader().getResource("/" + packageName.replaceAll("\\.","/"));
            if (url != null){
                File file = new File(url.getFile());
                for (File f : file.listFiles()){
                    if (f.isDirectory()){
                        doLoadResource(packageName+"."+f.getName());
                    }else {
                        classNames.add(packageName+"."+f.getName().replace(".class",""));
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void doRegister() {
        if (classNames != null && classNames.size() > 0){
            for (String className: classNames){
                try {
                    Class<?> clazz = Class.forName(className);
                    Object instance = clazz.newInstance();
                    String beanName = this.lowerFirstCase(clazz.getSimpleName());
                    beansMap.put(beanName,instance);
                    if (clazz.isAnnotationPresent(Controller.class)){
                        Controller controller = clazz.getAnnotation(Controller.class);
                        if (controller.value().trim().length() > 0){
                            beansMap.put(controller.value(),instance);
                        }
                    }
                    if (clazz.isAnnotationPresent(Service.class)){
                        Service service = clazz.getAnnotation(Service.class);
                        if (service.value().trim().length() > 0){
                            beansMap.put(service.value(),instance);
                        }
                    }
                     Class<?>[] cls = clazz.getInterfaces();
                    for (Class l : cls){
                        if (!l.equals(Object.class) && !l.equals(Serializable.class)){
                            beansMap.put(this.lowerFirstCase(l.getSimpleName()),instance);
                        }
                    }
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void doDepandent() {
        if (beansMap.isEmpty()){
            return;
        }
        for (Map.Entry entry: beansMap.entrySet()){
            entry.getKey();
            Field[] fields = entry.getValue().getClass().getDeclaredFields();
            for (Field f : fields){
                if(f.isAnnotationPresent(Autowired.class)){
                    try {
                        Autowired autowired = f.getAnnotation(Autowired.class);
                        String beanName;
                        if(autowired.value().trim().length() > 0){
                            beanName = autowired.value();
                        }else {
                            beanName = this.lowerFirstCase(f.getType().getSimpleName());
                        }
                        f.setAccessible(true);
                        f.set(entry.getValue(),beansMap.get(beanName));
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }

            }
        }
    }

    private String lowerFirstCase(String str){
        char [] chars = str.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }

}
